package xmwxapplet

import (
	"github.com/gin-gonic/gin"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/message"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/prices"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
)

// ------------ 订单相关请求处理 ---------------//

// GetOrderList 获取订单列表
func GetOrderList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	param := &request.OrderListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	memberInfo := memberdao.NewMemberDao().GetMemberInfoById(userId).Unwrap().(*membermodel.MembersModel)
	param.MemberId = memberInfo.UUID

	data := dao.NewOrderDao().GetOrderWxList(param)
	list := data.Unwrap().([]*request.OrderWxListRes)

	var productIds []string
	var PriceTypeList []*prices.PriceModel
	for _, item := range list {
		if item.State == 2 {
			productIds = append(productIds, item.ProductId)
		}
	}
	if len(productIds) > 0 {
		PriceTypeList = dao.NewOrderDao().GetOrderPriceTypeList(productIds).Unwrap().([]*prices.PriceModel)
		for _, item := range list {
			for _, pItem := range PriceTypeList {
				if item.ProductId == pItem.ProductId {
					item.PriceTypeInfo = pItem
					break
				}
			}
		}
	}

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       list,
	})(OK)
}

// GetOrderDetail 获取订单详情
func GetOrderDetail(ctx *gin.Context) {
	param := &struct {
		Id int `form:"id" binding:"required,gt=0"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindUri(param)).Unwrap()
	Response(ctx)("", CodeSuccess, dao.NewOrderDao().GetOrderDetail(param.Id).Unwrap())(OK)
}

// CloseTrade 关闭订单、结束订单
func CloseTrade(ctx *gin.Context) {
	// 取参数
	param := &request.GetTradeOrDeviceReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	// 结束订单业务逻辑
	//logic.NewWxLogic().HandleCloseTrade(param)

	// 响应
}

func HandleCheckOrderStatus(ctx *gin.Context) {
	param := &struct {
		Openid   string `json:"openid"`
		DeviceSn string `json:"deviceSn"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	orderInfo := dao.NewOrderDao().GetOrderInfoByOpenidAndSn(param.Openid, param.DeviceSn).Unwrap().(*orders.OrderModel)

	Response(ctx)("", CodeSuccess, &struct {
		Id        int    `json:"id"` // 订单id
		Openid    string `json:"openid"`
		TradeNo   string `json:"tradeNo"`  // 订单编号
		DeviceSn  string `json:"deviceSn"` // 设备Sn
		State     int8   `json:"state"`    // 订单状态
		FeeMode   int8   `json:"feeMode"`  // 计费模式
		ProductId string `json:"productId"`
		PlaceName string `json:"placeName"`
		PayAt     int64  `json:"payAt"`
		CreateAt  int64  `json:"createAt"`
		BeginAt   int64  `json:"beginAt"`
		Phone     string `json:"phone"`
		ProdType  uint8  `json:"prodType"`
	}{
		Id:        orderInfo.Id,
		Openid:    orderInfo.Openid,
		TradeNo:   orderInfo.TradeNo,
		DeviceSn:  orderInfo.DeviceSn,
		State:     orderInfo.State,
		FeeMode:   orderInfo.FeeMode,
		ProductId: orderInfo.ProductId,
		PlaceName: orderInfo.PlaceName,
		PayAt:     int64(orderInfo.PayAt),
		CreateAt:  int64(orderInfo.CreateAt),
		BeginAt:   int64(orderInfo.BeginAt),
		Phone:     orderInfo.Phone,
		ProdType:  orderInfo.ProdType,
	})(OK)
}

func HandleGetOrderInfo(ctx *gin.Context) {
	param := &struct {
		TradeNo string `json:"tradeNo"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	orderInfo := dao.NewOrderDao().WxGetOrderInfoByTradeNo(param.TradeNo).Unwrap().(*orders.OrderModel)
	userTime := int64(orderInfo.EndAt) - int64(orderInfo.PayAt)

	Response(ctx)("", CodeSuccess, &struct {
		Id              int    `json:"id"` // 订单id
		Openid          string `json:"openid"`
		TradeNo         string `json:"tradeNo"`  // 订单编号
		DeviceSn        string `json:"deviceSn"` // 设备Sn
		State           int8   `json:"state"`    // 订单状态
		FeeMode         int8   `json:"feeMode"`  // 计费模式
		ProductId       string `json:"productId"`
		PlaceName       string `json:"placeName"`
		PayAt           dingo.Time  `json:"payAt"`
		CreateAt        dingo.Time  `json:"createAt"`
		BeginAt         dingo.Time  `json:"beginAt"`
		EndAt           dingo.Time  `json:"endAt"`
		Phone           string `json:"phone"`
		Money           int64  `json:"money"`         // 订单总金额 - 单位分
		PayMoney        int64  `json:"payMoney"`      // 支付金额 - 单位分
		RefundMoney     int64  `json:"refundMoney"`   // 退款金额 - 单位分
		SettlementWay   int8   `json:"settlementWay"` // 结算方式 1: 微信支付
		SettlementMoney int64  `json:"settlementMoney"`
		UseTime         int64  `json:"useTime"`
	}{
		Id:              orderInfo.Id,
		Openid:          orderInfo.Openid,
		TradeNo:         orderInfo.TradeNo,
		DeviceSn:        orderInfo.DeviceSn,
		State:           orderInfo.State,
		FeeMode:         orderInfo.FeeMode,
		ProductId:       orderInfo.ProductId,
		PlaceName:       orderInfo.PlaceName,
		PayAt:           orderInfo.PayAt,
		CreateAt:        orderInfo.CreateAt,
		BeginAt:         orderInfo.BeginAt,
		EndAt:           orderInfo.EndAt,
		Phone:           orderInfo.Phone,
		Money:           orderInfo.Money,
		PayMoney:        orderInfo.PayMoney,
		RefundMoney:     orderInfo.RefundMoney,
		SettlementWay:   orderInfo.SettlementWay,
		SettlementMoney: orderInfo.SettlementMoney,
		UseTime:         userTime,
	})(OK)
}

// 微信订阅 订单归还提醒
func HandleOrderRemindRss(ctx *gin.Context) {
	param := &request.WxOrderRemindRss{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	Response(ctx)("", CodeSuccess, dao.NewMessageDao().InsertOrderRemindRss(param).Unwrap())(OK)
}

// HandleFixedRemindRss 微信订阅 好评提醒
func HandleFixedRemindRss(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.WxFixedRemindRss{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.MemberId = userId
	param.Type = 1

	Response(ctx)("", CodeSuccess, dao.NewMessageDao().InsertFixedRemindRss(param).Unwrap())(OK)
}

func HandleGetFixedRemindRss(ctx *gin.Context) {

	param := &message.MessageFixedModel{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.Type = 1

	Response(ctx)("", CodeSuccess, dao.NewMessageDao().GetFixedRemindRss(param).Unwrap())(OK)
}
